import { Editor, EditorEvents } from '@tiptap/core';
import { AiEditorOptions, InnerEditor } from '../../core/AiEditor';
import { AiEditorApp } from './AiApp'
import { defineCustomElement } from '../../commons/defineCustomElement';

export class OutlineApp extends HTMLElement implements AiEditorApp {
    appMessagesDiv: HTMLDivElement
    outline: HTMLDivElement

    event!: EditorEvents['create']
    editor!: Editor;
    options!: AiEditorOptions

    constructor() {
        super()
        this.appMessagesDiv = document.createElement('div')
        this.appMessagesDiv.classList.add('aie-container-app-messages')
        this.appendChild(this.appMessagesDiv)

        this.outline = document.createElement('div')
        this.outline.classList.add('aie-directory')
        this.appMessagesDiv.appendChild(this.outline)

        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.type === 'childList' || mutation.type === 'characterData') {
                    this.appMessagesDiv.scrollTop = this.appMessagesDiv.scrollHeight
                }
            })
        })
        // 配置MutationObserver
        const config = { childList: true, characterData: true }

        // 开始监听div的变化
        observer.observe(this.appMessagesDiv, config)
    }

    updateOutline() {
        if (this.editor) {
            this.outline.innerHTML = ""
            const h5 = document.createElement('h5')
            h5.innerText = '文档目录'
            this.outline.appendChild(h5)
            const outline: any[] = (this.editor as InnerEditor).aiEditor.getOutline()
            outline.forEach((heading: any) => {
                const a = document.createElement('a')
                a.href = '#'
                a.innerHTML = '&emsp;'.repeat(heading.level - 1) + heading.text
                a.addEventListener('click', () => {
                    this.editor.commands.focus(heading.pos + 1)
                    const {
                        state: { tr },
                        view: { dispatch }
                    } = this.editor
                    dispatch(tr.scrollIntoView())
                })
                this.outline.appendChild(a)
            })

            // this.outline.innerHTML = "<h5>文档目录</h5>" + (this.editor as InnerEditor).aiEditor.getOutline().map((heading) => {
            //     return `<a href="#${heading.id}" style="margin-left: ${heading.level - 1}0px;">${heading.text}</a>`
            // }).join("<br />")
        }
    }

    onCreate(event: EditorEvents['create'], options: AiEditorOptions): void {
        this.event = event
        this.editor = event.editor
        this.options = options
        this.updateOutline()
    }

    onTransaction(event: EditorEvents['transaction']): void {
        if (!event.transaction.getMeta("blur")) {
            this.updateOutline()
        }
    }
}

defineCustomElement('aie-outline-app', OutlineApp)
